from os import abort

from flask import Blueprint, jsonify, request

from deploy.GitDeploy import deploy
from entity.models import User
from settings import Setting
from util.WebUtil import GITEE, get_web_hook_token

api_index = Blueprint('api_index', __name__)
api_index.url_prefix = '/api'


@api_index.route("/user")
def get_user():
    user = User.query.filter_by(name='admin').first()
    print(user)
    return jsonify({'data': user.id})


@api_index.route("/deploy/hook", methods=['GET', 'POST'])
def webhook():
    print(request.json)
    if request.method == 'GET':
        if is_verify(request):
            return jsonify({'status': 'success'}), 200
        else:
            return jsonify({'status': 'bad token'}), 401
    elif request.method == 'POST':
        # and request.json['ref'] == 'refs/heads/dev':
        if is_verify(request) and request.json['ref'] == 'refs/heads/{}'.Setting.branch:
            if deploy():
                return jsonify({'status': 'success'}), 200
            else:
                return jsonify({'status': 'deploy failed'}), 503
        else:
            return jsonify({'status': 'bad token'}), 401
    else:
        abort(400)


def is_verify(req):
    return get_web_hook_token(req, parm=GITEE) == Setting.token


@api_index.route("/test", methods=["POST"])
def get_user11():
    request.json
    print(request.json)
    return jsonify({'data': "牛皮", 'ok': True})
